import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:3000/api',
  timeout: 10000,
  withCredentials: true // 启用跨域请求时发送cookie
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 在请求发送前可以进行一些处理
    console.log('API请求:', config.url)
    
    // 添加时间戳防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }
    
    return config
  },
  error => {
    // 请求错误处理
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    // 对响应数据进行处理
    console.log('API响应:', response.config.url, response.status)
    return response.data
  },
  error => {
    // 响应错误处理
    console.error('响应错误:', error.response?.status, error.response?.data?.message || error.message)
    
    // 如果是401未授权错误，可能是会话过期
    if (error.response && error.response.status === 401) {
      console.warn('检测到会话可能已过期')
      // 不是登录相关的请求时，清除本地存储中的用户信息
      if (!error.config.url.includes('/auth/')) {
        console.warn('清除本地存储的用户信息')
        localStorage.removeItem('weatherAppUser')
      }
    }
    
    return Promise.reject(error)
  }
)

// 天气相关API
export const weatherApi = {
  // 获取特定城市天气
  getCityWeather: (city, province) => api.get(`/weather/${city}/${province}`),
  
  // 获取天气预报详情
  getCityForecastDetail: (city, province) => api.get(`/weather/forecast/${city}/${province}`),
  
  // 获取热门城市 - 使用和风天气API路径
  getPopularCityWeather: (params) => api.get('/weather/geo/v2/city/top', { params }),
  
  // 城市搜索 - 使用和风天气API路径
  searchCity: (location, options = {}) => api.get('/weather/geo/v2/city/lookup', {
    params: {
      location,
      ...options
    }
  }),
  
  // 获取多个城市天气
  getMultiCityWeather: (cities) => api.post('/weather/multi', { cities })
}

// 用户认证相关API
export const authApi = {
  // 注册
  register: (userData) => api.post('/auth/register', userData),
  
  // 登录
  login: (credentials) => api.post('/auth/login', credentials),
  
  // 登出
  logout: () => api.get('/auth/logout')
}

// 用户相关API
export const userApi = {
  // 获取当前用户信息
  getCurrentUser: () => api.get('/users/me'),
  
  // 更新用户信息
  updateUser: (userData) => api.patch('/users/updateMe', userData),
  
  // 获取收藏城市列表
  getFavorites: () => api.get('/users/favorites'),
  
  // 添加收藏城市
  addFavorite: (city, province) => api.post('/users/favorites', { city, province }),
  
  // 移除收藏城市
  removeFavorite: (city, province) => api.delete('/users/favorites', { data: { city, province } })
}

// 预警相关API
export const warningApi = {
  // 获取当前预警信息
  getCurrentWarnings: (location) => api.get('/warnings/current', { params: { location } }),
  
  // 获取用户的所有预警设置
  getUserWarnings: () => api.get('/warnings'),
  
  // 创建预警设置
  createWarning: (warningData) => api.post('/warnings', warningData),
  
  // 获取单个预警设置
  getWarning: (id) => api.get(`/warnings/${id}`),
  
  // 更新预警设置
  updateWarning: (id, warningData) => api.patch(`/warnings/${id}`, warningData),
  
  // 删除预警设置
  deleteWarning: (id) => api.delete(`/warnings/${id}`),
  
  // 发送测试邮件
  sendTestEmail: () => api.get('/warnings/test-email')
}

export default {
  weatherApi,
  authApi,
  userApi,
  warningApi
} 